package com.dashen.general.server.config.security.user;

import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.factory.PasswordEncoderFactories;

import java.util.HashSet;
import java.util.Optional;

/**
 * @auther barry
 * @date 2019/1/16
 */
public class GeneralUserDetailsServiceImpl implements UserDetailsService {

    public final static HashSet<GeneralUserDetailsImpl> USERS =
            new HashSet<GeneralUserDetailsImpl>();

    static {
        USERS.add(new GeneralUserDetailsImpl(1, "user", encoder("12345")));
        USERS.add(new GeneralUserDetailsImpl(1, "user1", encoder("12345")));
        USERS.add(new GeneralUserDetailsImpl(2, "user2", encoder("12345")));
        USERS.add(new GeneralUserDetailsImpl(3, "user3", encoder("12345")));
        USERS.add(new GeneralUserDetailsImpl(4, "user4", encoder("12345")));
    }

    public static String encoder(String pass){
        return  PasswordEncoderFactories.createDelegatingPasswordEncoder().encode(pass);
    }


    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Optional<GeneralUserDetailsImpl> user = USERS.stream()
                .filter((u) -> u.getUsername().equals(username))
                .findFirst();

        if(!user.isPresent()) {
            throw new UsernameNotFoundException("there's no user founded!");
        }
        else {
            return user.get();
        }
    }
}
